﻿using System;
using RestSharp;

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace ConsoleApp1
{
    class Program
    {
        public static JObject Readjson(string jsonfile)
        {
            JObject o = null;
            using (System.IO.StreamReader file = System.IO.File.OpenText(jsonfile))
            {
                using (JsonTextReader reader = new JsonTextReader(file))
                {
                    o = (JObject)JToken.ReadFrom(reader);
                }
            }
            return o;
        }

        public static JObject SendPostRequest(string url, JObject data)
        {
            try
            {
                // 构造请求客户端对象, 指定api服务器的地址
                var client = new RestClient(url);
                //client.Authenticator = new HttpBasicAuthenticator("username", "password");

                // 构造请求对象, 指定请求url以及请求方法
                var request = new RestRequest(Method.POST);
                request.AddHeader("Cache-Control", "no-cache");
                request.AddHeader("Accept", "application/json");
                request.AddHeader("Content-Type", "application/json");
                // 向body中添加json数据
                request.AddParameter("application/json; charset=utf-8", JsonConvert.SerializeObject(data), ParameterType.RequestBody);

                // 发送请求, 得到返回结果
                IRestResponse response = client.Execute(request);

                // 提取返回的结果
                var content = response.Content;
                Console.WriteLine(content);

                // 将返回结果反序列化为JObject 对象
                return JsonConvert.DeserializeObject<JObject>(response.Content);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return null;
            }                        
        }

        public static void Main(string[] args)
        {
            // 准备json数据
            var json_from_client = Readjson("Topology.json"); // 注：这里直接读json文件


            // 请求目标: python+fastapi, 格式: { "graph": xxx, "params": null },
            JObject data = new JObject();
            data["graph"] = json_from_client;
            //data["params"] = null;

            // 发送post请求
            //JObject result = SendPostRequest("http://127.0.0.1:8008/vnetoy/NetworkCalculate", data);

            // 请求目标: 阿里云函数
            data = json_from_client;
            // 发送post请求
            JObject result = SendPostRequest("https://1825138619804807.cn-zhangjiakou.fc.aliyuncs.com/2016-08-15/proxy/jl/api/v1/calculate", data);

            // 打印结果
            Console.WriteLine(JsonConvert.SerializeObject(result));
        }
    }
}
